package tm.testing;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import com.jme.bounding.BoundingSphere;
import com.jme.scene.Spatial;
import com.jme.util.export.binary.BinaryImporter;
import com.jmex.model.converters.FormatConverter;
import com.jmex.model.converters.ObjToJme;

public class Structure {
	
	private Spatial spatial;
	private String identifier;
	private Properties properties;
	
	public Structure(String id) {
		this.identifier = id;
	}
	
	public void setSpatial(Spatial sp) {
		spatial = sp;
	}
	
	public Spatial getSpatial() {
		return spatial;
	}
	
	public void setProperty(Properties p) {
		properties = p;
	}
	
	public Properties getProperty() {
		return properties;
	}
	
	public String getIdentifier() {
		return identifier;
	}
	
	public void setPosition(Coordinate c, MapGrid mapGrid) throws MapElementIndexOutOfBoundsException {
		spatial.setLocalTranslation(mapGrid.getElementCoord(c.getX(), c.getY(), mapGrid.defaultHeight));
		spatial.updateRenderState();
	}
	
	public void loadObjModel(String file, float scale) {
	      URL modelloc=Road.class.getClassLoader().getResource(file);

	      // Create something to convert .obj format to .jme
	      FormatConverter converter=new ObjToJme();
	      // Point the converter to where it will find the .mtl file from
	      converter.setProperty("mtllib",modelloc);

	      // This byte array will hold my .jme file
	      ByteArrayOutputStream BO=new ByteArrayOutputStream();

	      // Use the format converter to convert .obj to .jme
	     try {
	    	  converter.convert(modelloc.openStream(), BO);
	    	  Spatial model;
	    	  model = (Spatial)BinaryImporter.getInstance().load(new ByteArrayInputStream(BO.toByteArray()));
	    	  model.setName("S_"+identifier);
	    	  model.setModelBound(new BoundingSphere());
	    	  model.updateModelBound();
	    	  model.setLocalScale(scale);
		      model.updateRenderState();
		      spatial = model;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			spatial = null;
		}
	}
}
